<template>
  <div class="dashboard-container">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="nav-left">
        <div class="logo">
          <el-icon size="32"><Monitor /></el-icon>
          <span class="brand-name">Cyan-Note</span>
        </div>
        <div class="welcome-info">
          <h2 class="welcome-title">{{ getWelcomeTitle }}</h2>
          <p class="user-info">{{ getUserInfo }}</p>
        </div>
      </div>
      
      <div class="nav-right">
        <div class="user-menu">
          <el-dropdown @command="handleUserCommand" trigger="click">
            <div class="user-avatar">
              <el-avatar :size="40" :src="authStore.userAvatar || undefined">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="user-name">{{ authStore.userName }}</span>
              <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人资料
                </el-dropdown-item>
                <el-dropdown-item command="settings">
                  <el-icon><Setting /></el-icon>
                  系统设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 状态卡片 -->
      <div class="status-cards">
        <div class="card login-status">
          <div class="card-header">
            <el-icon size="24" color="#4ECDC4"><SuccessFilled /></el-icon>
            <h3>登录状态</h3>
          </div>
          <div class="card-content">
            <div class="status-item">
              <span class="label">登录状态:</span>
              <el-tag type="success">已登录</el-tag>
            </div>
            <div class="status-item">
              <span class="label">用户类型:</span>
              <el-tag :type="getUserTypeTag">{{ getUserTypeText }}</el-tag>
            </div>
            <div class="status-item">
              <span class="label">用户名称:</span>
              <span class="value">{{ authStore.userName }}</span>
            </div>
            <div class="status-item" v-if="authStore.shopName">
              <span class="label">所属店铺:</span>
              <span class="value">{{ authStore.shopName }}</span>
            </div>
          </div>
        </div>

        <div class="card permissions">
          <div class="card-header">
            <el-icon size="24" color="#F39C12"><Key /></el-icon>
            <h3>权限信息</h3>
          </div>
          <div class="card-content">
            <div class="permission-count">
              <span class="count">{{ authStore.permissions.length }}</span>
              <span class="text">项权限</span>
            </div>
            <div class="permission-list" v-if="authStore.permissions.length > 0">
              <el-tag 
                v-for="permission in displayPermissions" 
                :key="permission"
                size="small"
                class="permission-tag"
              >
                {{ permission }}
              </el-tag>
              <el-tag 
                v-if="authStore.permissions.length > 5"
                size="small"
                type="info"
                class="permission-tag"
              >
                +{{ authStore.permissions.length - 5 }}更多
              </el-tag>
            </div>
            <div v-else class="no-permissions">
              <span>无特殊权限</span>
            </div>
          </div>
        </div>

        <div class="card connection-status">
          <div class="card-header">
            <el-icon size="24" :color="connectionColor"><Connection /></el-icon>
            <h3>连接状态</h3>
          </div>
          <div class="card-content">
            <div class="status-item">
              <span class="label">后端连接:</span>
              <el-tag :type="connectionStatus.type">{{ connectionStatus.text }}</el-tag>
            </div>
            <div class="status-item">
              <span class="label">API地址:</span>
              <span class="value">{{ apiBaseUrl }}</span>
            </div>
            <div class="status-item">
              <span class="label">Token状态:</span>
              <el-tag type="success">有效</el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 功能按钮 -->
      <div class="action-buttons">
        <el-button type="primary" size="large" @click="refreshUserInfo">
          <el-icon><Refresh /></el-icon>
          刷新用户信息
        </el-button>
        <el-button type="success" size="large" @click="testConnection">
          <el-icon><Connection /></el-icon>
          测试连接
        </el-button>
        <el-button type="info" size="large" @click="viewProfile">
          <el-icon><User /></el-icon>
          查看资料
        </el-button>
        <el-button type="warning" size="large" @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>

      <!-- 调试信息 -->
      <div class="debug-info" v-if="showDebugInfo">
        <div class="debug-card">
          <div class="debug-header">
            <el-icon><InfoFilled /></el-icon>
            <h3>调试信息</h3>
            <el-button size="small" text @click="showDebugInfo = false">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
          <div class="debug-content">
            <pre>{{ debugData }}</pre>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
  Monitor,
  User,
  ArrowDown,
  Setting,
  SwitchButton,
  SuccessFilled,
  Key,
  Connection,
  Refresh,
  InfoFilled,
  Close
} from '@element-plus/icons-vue'
import { useAuthStore } from '@renderer/store/modules/auth'
import { testConnection } from '@renderer/api/login'

// 路由和状态管理
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const showDebugInfo = ref(false)
const connectionStatus = ref({
  type: 'success' as 'success' | 'warning' | 'danger',
  text: '已连接'
})

// 计算属性
const apiBaseUrl = computed(() => {
  return import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
})

const getWelcomeTitle = computed(() => {
  const timeHour = new Date().getHours()
  let greeting = ''
  
  if (timeHour < 6) greeting = '深夜好'
  else if (timeHour < 9) greeting = '早上好'
  else if (timeHour < 12) greeting = '上午好'
  else if (timeHour < 14) greeting = '中午好'
  else if (timeHour < 17) greeting = '下午好'
  else if (timeHour < 19) greeting = '傍晚好'
  else greeting = '晚上好'
  
  return `${greeting}，${authStore.userName}`
})

const getUserInfo = computed(() => {
  const typeMap = {
    'super_admin': '超级管理员',
    'manager': '店长',
    'worker': '打手'
  }
  
  let info = `您的身份是${typeMap[authStore.userType!] || '未知'}`
  if (authStore.shopName) {
    info += `，管理${authStore.shopName}`
  }
  
  return info
})

const getUserTypeText = computed(() => {
  const typeMap = {
    'super_admin': '超级管理员',
    'manager': '店长',
    'worker': '打手'
  }
  return typeMap[authStore.userType!] || '未知'
})

const getUserTypeTag = computed(() => {
  const tagMap = {
    'super_admin': 'danger',
    'manager': 'primary',
    'worker': 'success'
  }
  return tagMap[authStore.userType!] || 'info'
})

const displayPermissions = computed(() => {
  return authStore.permissions.slice(0, 5)
})

const connectionColor = computed(() => {
  return connectionStatus.value.type === 'success' ? '#4ECDC4' : 
         connectionStatus.value.type === 'warning' ? '#F39C12' : '#E74C3C'
})

const debugData = computed(() => {
  return JSON.stringify({
    userInfo: authStore.userInfo,
    permissions: authStore.permissions,
    token: authStore.token ? `${authStore.token.substring(0, 20)}...` : null,
    loginTime: new Date().toISOString(),
    environment: import.meta.env
  }, null, 2)
})

// 组件挂载
onMounted(() => {
  checkConnection()
  
  console.log('工作台已加载:', {
    userType: authStore.userType,
    userName: authStore.userName,
    permissions: authStore.permissions.length
  })
})

// 检查连接状态
const checkConnection = async () => {
  try {
    await testConnection()
    connectionStatus.value = { type: 'success', text: '连接正常' }
  } catch (error) {
    console.error('连接测试失败:', error)
    connectionStatus.value = { type: 'danger', text: '连接失败' }
  }
}

// 刷新用户信息
const refreshUserInfo = async () => {
  try {
    await authStore.refreshUserInfo()
    ElMessage.success('用户信息已刷新')
  } catch (error: any) {
    console.error('刷新用户信息失败:', error)
    ElMessage.error(error.message || '刷新失败')
  }
}

// 测试连接
const testConnection = async () => {
  try {
    await checkConnection()
    ElMessage.success('连接测试成功')
  } catch (error) {
    ElMessage.error('连接测试失败')
  }
}

// 查看资料
const viewProfile = () => {
  showDebugInfo.value = !showDebugInfo.value
}

// 处理用户菜单命令
const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      viewProfile()
      break
    case 'settings':
      ElMessage.info('系统设置功能开发中...')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '确认退出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await authStore.logout()
    
    ElNotification({
      title: '退出成功',
      message: '已安全退出登录',
      type: 'success',
      duration: 2000
    })
    
    router.push('/login')
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error)
      ElMessage.error('退出登录失败')
    }
  }
}

console.log('Dashboard组件已加载')
</script>

<style scoped lang="scss">
// 变量定义
$primary-color: #4ECDC4;
$success-color: #27AE60;
$warning-color: #F39C12;
$danger-color: #E74C3C;
$info-color: #3498DB;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.8);

.dashboard-container {
  width: 100%;
  height: 100vh;
  background: 
    radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.3) 0%, transparent 50%),
    linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow-y: auto;
}

// 顶部导航栏
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  
  .nav-left {
    display: flex;
    align-items: center;
    gap: 32px;
    
    .logo {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .el-icon {
        color: $primary-color;
      }
      
      .brand-name {
        font-size: 24px;
        font-weight: 800;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
    
    .welcome-info {
      .welcome-title {
        font-size: 20px;
        font-weight: 600;
        color: $text-primary;
        margin: 0 0 4px 0;
      }
      
      .user-info {
        font-size: 14px;
        color: $text-secondary;
        margin: 0;
      }
    }
  }
  
  .nav-right {
    .user-menu {
      .user-avatar {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 8px 16px;
        border-radius: 20px;
        background: rgba(255, 255, 255, 0.1);
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(255, 255, 255, 0.15);
        }
        
        .user-name {
          color: $text-primary;
          font-weight: 600;
        }
        
        .dropdown-icon {
          color: $text-secondary;
          font-size: 12px;
        }
      }
    }
  }
}

// 主内容区域
.main-content {
  padding: 40px;
}

// 状态卡片
.status-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
  
  .card {
    background: rgba(255, 255, 255, 0.25);
    backdrop-filter: blur(25px);
    border: 1px solid rgba(255, 255, 255, 0.4);
    border-radius: 20px;
    padding: 24px;
    box-shadow: 
      0 12px 40px rgba(0, 0, 0, 0.2),
      0 0 60px rgba(255, 255, 255, 0.1),
      inset 0 1px 0 rgba(255, 255, 255, 0.4);
    
    .card-header {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 20px;
      
      h3 {
        font-size: 16px;
        font-weight: 600;
        color: $text-primary;
        margin: 0;
      }
    }
    
    .card-content {
      .status-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 14px;
          color: $text-secondary;
        }
        
        .value {
          font-size: 14px;
          font-weight: 600;
          color: $text-primary;
        }
      }
      
      .permission-count {
        text-align: center;
        margin-bottom: 16px;
        
        .count {
          font-size: 32px;
          font-weight: 800;
          color: $primary-color;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .text {
          font-size: 14px;
          color: $text-secondary;
          margin-left: 8px;
        }
      }
      
      .permission-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .permission-tag {
          font-size: 12px;
        }
      }
      
      .no-permissions {
        text-align: center;
        color: $text-secondary;
        font-size: 14px;
      }
    }
  }
}

// 功能按钮
.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  justify-content: center;
  margin-bottom: 32px;
  
  .el-button {
    min-width: 120px;
  }
}

// 调试信息
.debug-info {
  .debug-card {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 16px;
    overflow: hidden;
    
    .debug-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 20px;
      background: rgba(255, 255, 255, 0.1);
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);
      
      h3 {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 600;
        color: $text-primary;
        margin: 0;
      }
    }
    
    .debug-content {
      padding: 20px;
      
      pre {
        background: rgba(0, 0, 0, 0.3);
        border-radius: 8px;
        padding: 16px;
        color: $text-primary;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 12px;
        line-height: 1.5;
        overflow-x: auto;
        margin: 0;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    .top-nav {
      flex-direction: column;
      gap: 16px;
      padding: 20px;
      
      .nav-left {
        flex-direction: column;
        gap: 16px;
        text-align: center;
      }
    }
    
    .main-content {
      padding: 20px;
    }
    
    .status-cards {
      grid-template-columns: 1fr;
    }
    
    .action-buttons {
      flex-direction: column;
      align-items: stretch;
    }
  }
}
</style>